package com.lizhangjun.nim.toolkit;

import com.lizhangjun.nim.constant.ImConstant;
import org.apache.commons.lang3.StringUtils;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

/**
 * rocket mq消息队列
 */
@Service
public class RocketMQProducer extends MQProducer {

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @Override
    public void sendMsg(String body) {
        sendAsyncMsg(ImConstant.TOPIC_IM,ImConstant.TAG_CHAT, body);
    }

    /**
     * 发送异步消息
     * @param topic 主题
     * @param tag 标签
     * @param body 消息内容
     */
    public void sendAsyncMsg(String topic, String tag, String body){
        if (StringUtils.isNoneBlank(topic, tag)){
            rocketMQTemplate.asyncSend(topic + ":" + tag, body, new SendCallback() {
                @Override
                public void onSuccess(SendResult sendResult) {
                    //持久化
                    //System.out.println(body);
                }

                @Override
                public void onException(Throwable throwable) {
                    //重试
                }
            });
        }else {
            rocketMQTemplate.asyncSend(topic, body, new SendCallback() {
                @Override
                public void onSuccess(SendResult sendResult) {
                    //持久化
                    System.out.println(body);
                }

                @Override
                public void onException(Throwable throwable) {
                    //重试
                }
            });
        }
    }
}
